﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using FineUI;
using Maticsoft.DBUtility;

namespace mydddd.Web.code
{
    public class FineuiHelper
    {
        public class Grid
        {
            /// <summary>
            /// 动态创建Grid结构，在 Page_Init事件里执行（不是Page_Load事件里）
            /// </summary>
            /// <param name="Grid1">The grid1.</param>
            /// <param name="dt">The dt.</param>
            public static void CreatGridStructByDataTable(FineUI.Grid Grid1, DataTable dt)
            {
                FineUI.BoundField bf;

                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    bf = new FineUI.BoundField();
                    bf.DataField = dt.Columns[i].Caption;
                    bf.DataFormatString = "{0}";
                    bf.HeaderText = dt.Columns[i].Caption;
                    Grid1.Columns.Add(bf);
                }
            }

            /// <summary>
            /// 获取选中行的主id，第一主键
            /// </summary>
            /// <param name="grid">FineUI.Grid</param>
            /// <returns></returns>
            public static string GetDataKeysBySelectedRow(FineUI.Grid grid)
            {
                return GetDataKeysBySelectedRow(grid, 0);
            }

            /// <summary>
            /// 获取选中行的主id
            /// </summary>
            /// <param name="grid">FineUI.Grid</param>
            /// <param name="keyNumIndex">第几个主键（从0开始）</param>
            /// <returns></returns>
            public static string GetDataKeysBySelectedRow(FineUI.Grid grid, int keyNumIndex)
            {
                //需要正确设置grid DataKeyNames主键列名
                int[] selections = grid.SelectedRowIndexArray;//获取选中行
                if (selections.Length == 0)
                {
                    return string.Empty;
                }

                StringBuilder sb = new StringBuilder();
                foreach (int rowIndex in selections)
                {
                    sb.Append("," + grid.DataKeys[rowIndex][keyNumIndex]);//获取每行第keyNumIndex个主键
                }
                return sb.ToString().Substring(1);
            }

            /// <summary>
            /// 绑定FineUI.Grid分页方法
            /// </summary>
            /// <param name="grid">FineUI.Grid</param>
            /// <param name="tableName">表名</param>
            /// <param name="strSql">where条件(加and)</param>
            /// <param name="orderbyColumn">排序条件</param>
            public void BindFineUI(FineUI.Grid grid, string tableName, string strSql, string orderbyColumn)
            {
                BindFineUI(" * ", grid, tableName, strSql, orderbyColumn);
            }

            /// <summary>
            /// 绑定FineUI.Grid分页方法
            /// </summary>
            /// <param name="columns">显示列名</param>
            ///  <param name="grid">FineUI.Grid</param>
            /// <param name="tableName">表名</param>
            /// <param name="whereSql">where条件(加and)</param>
            /// <param name="orderbyColumn">排序条件</param>
            public static void BindFineUI(string columns, FineUI.Grid grid, string tableName, string whereSql, string orderbyColumn)
            {
                int pageindex = grid.PageIndex;//fineui有时莫名其妙值会变成-1

                if (orderbyColumn.Length == 0)
                {
                    orderbyColumn = string.Format(" {0} {1} ", grid.SortField, grid.SortDirection);
                }

                string sql = string.Format(@"select  {0},row_number() over(order by {1}) rid into #tt from {2} 
                                                                where 1=1 {3} Order By {1}  select * from  #tt where rid> {4} and rid<={5} drop table  #tt", 
                                            columns, orderbyColumn, tableName, whereSql, grid.PageSize * pageindex, grid.PageSize * (pageindex + 1));
                grid.RecordCount = GetdataTableCount(string.Format("select count(1) from {0}  where 1=1 {1}", tableName, whereSql));
                DataTable dt = GetPagedDataTable(sql);
                DataView view1 = dt.DefaultView;
                view1.Sort = orderbyColumn;
                grid.DataSource = null;
                grid.DataSource = view1;
                grid.DataBind();
            }

            /// <summary>
            /// 绑定FineUI.Grid分页方法
            /// </summary>
            /// <param name="columns">显示列名</param>
            ///  <param name="grid">FineUI.Grid</param>
            /// <param name="tableName">表名</param>
            /// <param name="whereSql">where条件(加and)</param>
            /// <param name="dic">条件参数和赋值</param>
            /// <param name="orderbyColumn">排序条件</param>
            public static void BindFineUI(string columns, FineUI.Grid grid, string tableName, string whereSql, Dictionary<string, object> dic, string orderbyColumn)
            {
                if (orderbyColumn.Length == 0)
                {
                    orderbyColumn = string.Format(" {0} {1} ", grid.SortField, grid.SortDirection);
                }

                StringBuilder sb = new StringBuilder();
                List<SqlParameter> sqlParams = new List<SqlParameter>();
                if (dic.Count > 0)
                {
                    foreach (KeyValuePair<string, object> keyDic in dic)
                    {
                        sb.Append(" and " + keyDic.Key + " like @" + keyDic.Key);
                        sqlParams.Add(new SqlParameter(keyDic.Key, keyDic.Value));
                    }
                }
                else
                {
                    sb.Append(string.Empty);
                }

                SqlParameter[] pars = sqlParams.ToArray();

                int pageindex = grid.PageIndex;

                string sql = 
                    string.Format(@"select  {0},row_number() over(order by {1}) rid into #tt from {2} 
                                                        where 1=1 {3} {4} select * from  #tt where rid> {5} and rid<={6} Order By {1} drop table  #tt", 
                                    columns, orderbyColumn, tableName, whereSql, sb.ToString(), grid.PageSize * pageindex, grid.PageSize * (pageindex + 1));
                grid.RecordCount = GetdataTableCount(string.Format("select count(1) from {0}  where 1=1 {1} {2} ", tableName, whereSql, sb.ToString()), pars);
                DataTable dt = GetPagedDataTable(sql, pars);
                DataView view1 = dt.DefaultView;
                view1.Sort = orderbyColumn;
                grid.DataSource = null;
                grid.DataSource = view1;
                grid.DataBind();
            }

            /// <summary>
            /// 查询数据库记录条数
            /// </summary>
            /// <param name="sql"></param>
            /// <returns></returns>
            private static int GetdataTableCount(string sql)
            {
                string cnt = DbHelperSQL.Query(sql).Tables[0].Rows[0][0].ToString();
                return Convert.ToInt32(cnt);
            }
            /// <summary>
            /// 查询数据库记录条数
            /// </summary>
            /// <param name="sql"></param>
            /// <returns></returns>
            private static int GetdataTableCount(string sql, SqlParameter[] par)
            {
                string cnt = DbHelperSQL.Query(sql, par).Tables[0].Rows[0][0].ToString();
                return Convert.ToInt32(cnt);
            }

            /// <summary>
            /// 数据库分页查询语句
            /// </summary>
            /// <returns></returns>
            private static DataTable GetPagedDataTable(string sql, SqlParameter[] par)
            {
                DataSet ds = DbHelperSQL.Query(sql,par);
                return ds.Tables[0];
            }
            /// <summary>
            /// 数据库分页查询语句
            /// </summary>
            /// <returns></returns>
            private static DataTable GetPagedDataTable(string sql)
            {
                DataSet ds = DbHelperSQL.Query(sql);
                return ds.Tables[0];
            }
        }

        public class Alert
        {
            public static void AlertInforAndRedirect(string message, string url)
            {
                FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Information, ActiveWindow.GetHidePostBackReference("self.location='" + url + "'"));
            }

            /// <summary>
            /// 提示信息(弹层用)
            /// </summary>
            /// <param name="message">内容</param>
            /// <param name="isPostBackReference">是否回发刷新页面</param>
            public static void AlertInfor(string message, bool isPostBackReference)
            {
                if (isPostBackReference)
                {
                    //弹层页用,结合window的Onclose事件使用
                    FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Information, ActiveWindow.GetHidePostBackReference());

                    //弹层页用
                    //Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Information, ActiveWindow.GetHideRefreshReference());

                    //单页 并刷新当前页
                    //Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Information, "window.location.reload()");
                }
                else
                    FineUI.Alert.ShowInParent(message, MessageBoxIcon.Information);

            }

            /// <summary>
            /// 不带关闭按钮的提示框(结合window的Onclose事件使用)
            /// </summary>
            /// <param name="message">消息</param>
            public static void AlertInforNoClose(string message)
            {
                AlertInforNoClose(message, ActiveWindow.GetHidePostBackReference());
            }

            /// <summary>
            /// 不带关闭按钮的提示框
            /// </summary>
            /// <param name="message">消息</param>
            /// <param name="js">点击确定后执行的js脚本</param>
            public static void AlertInforNoClose(string message, string js)
            {
                string jsStr = string.Format(@" Ext.Msg.show({{ 
                                    title : '提示对话框', 
                                    msg : '{0}', 
                                    buttons: Ext.Msg.OK, 
                                    fn:function(){{{1}}},
                                    closable: false 
                                    }}); ", message, js);

                PageContext.RegisterStartupScript(jsStr);
            }

            /// <summary>
            /// 提示信息（单页用 并刷新当前页）
            /// </summary>
            /// <param name="message">内容</param>
            /// <param name="isPostBackReference">是否回发刷新页面</param>
            public static void AlertInforBySingerPage(string message, bool isPostBackReference)
            {
                if (isPostBackReference)
                {
                    //单页 并刷新当前页
                    FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Information, "window.location.reload()");
                }
                else
                    FineUI.Alert.ShowInParent(message, MessageBoxIcon.Information);

            }

            /// <summary>
            /// 报错信息
            /// </summary>
            /// <param name="message">内容</param>
            /// <param name="isPostBackReference">是否回发刷新页面</param>
            public static void AlertError(string message, bool isPostBackReference)
            {
                if (isPostBackReference)
                    FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Error, ActiveWindow.GetHidePostBackReference());
                else
                    FineUI.Alert.ShowInParent(message, MessageBoxIcon.Error);
            }

            /// <summary>
            /// 疑问信息
            /// </summary>
            /// <param name="message">内容</param>
            /// <param name="isPostBackReference">是否回发刷新页面</param>
            public static void AlertQuestion(string message, bool isPostBackReference)
            {
                if (isPostBackReference)
                    FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Question, ActiveWindow.GetHidePostBackReference());
                else
                    FineUI.Alert.ShowInParent(message, MessageBoxIcon.Question);
            }

            /// <summary>
            /// 警告信息
            /// </summary>
            /// <param name="message">内容</param>
            /// <param name="isPostBackReference">是否回发刷新页面</param>
            public static void AlertWarning(string message, bool isPostBackReference)
            {
                if (isPostBackReference)
                    FineUI.Alert.ShowInParent(message, "提示对话框", MessageBoxIcon.Warning, ActiveWindow.GetHidePostBackReference());
                else
                    FineUI.Alert.ShowInParent(message, MessageBoxIcon.Warning);
            }

            /// <summary>
            /// 子页面关闭并在父业面跳转
            /// </summary>
            /// <param name="url"></param>
            public static void ParentRedirect(string url)
            {
                PageContext.RegisterStartupScript(ActiveWindow.GetHidePostBackReference(url));
            }
        }

        public class DropDownList
        {
            /// <summary>
            /// 绑定下拉框
            /// </summary>
            /// <param name="dll">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            public static void Bind(FineUI.DropDownList dll, string tableName, string textName, string valueName)
            {
                Bind(dll, tableName, textName, valueName, string.Empty);
            }

            /// <summary>
            /// 绑定下拉框
            /// </summary>
            /// <param name="dll">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            /// <param name="whereSql">sql条件，注意会有注入危险(不用加where)</param>
            public static void Bind(FineUI.DropDownList dll, string tableName, string textName, string valueName, string whereSql)
            {
                string sql = string.Format("select {0},{1} from {2} {3} ", textName, valueName, tableName, (whereSql.Length > 0 ? " where " + whereSql : string.Empty));

                //DataSet ds = DbHelperSQL.Query(sql);

                //if (ds.Tables[0].Rows.Count > 0)
                //{

                //    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                //    {
                //        dll.Items.Add(new FineUI.ListItem(ds.Tables[0].Rows[i][textName].ToString(), ds.Tables[0].Rows[i][valueName].ToString()));
                //    }
                //}

                //以下方法 会给textName 添加\r\n，导致不能正常取值，原因不清楚。

                dll.DataTextField = textName;
                dll.DataValueField = valueName;
                dll.DataSource = DbHelperSQL.Query(sql);
                dll.DataBind();

                //在业务逻辑里设置强制选中
                //if (dll.Items != null && dll.Items.Count > 0) dll.Items[0].Selected = true;
            }

            /// <summary>
            /// 绑定枚举类型到下拉框 //Bind(newstype, typeof (EnumClass .NewsType));
            /// </summary>
            /// <param name="dll"> 下拉框</param>
            /// <param name="enumType"> 枚举类型</param>
            public static void Bind(FineUI.DropDownList dll, Type enumType)
            {
                foreach (int i in Enum.GetValues(enumType))
                {
                    dll.Items.Add(new FineUI.ListItem(Enum.GetName(enumType, i), i.ToString()));
                }
            }
        }

        public class CheckBoxList
        {
            /// <summary>
            /// 绑定复选框列表
            /// </summary>
            /// <param name="cbl">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            public static void Bind(FineUI.CheckBoxList cbl, string tableName, string textName, string valueName)
            {
                Bind(cbl, tableName, textName, valueName, string.Empty);
            }

            /// <summary>
            /// 绑定复选框列表
            /// </summary>
            /// <param name="cbl">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            /// <param name="whereSql">sql条件，注意会有注入危险(不用加where)</param>
            public static void Bind(FineUI.CheckBoxList cbl, string tableName, string textName, string valueName, string whereSql)
            {
                string sql = string.Format("select {0},{1} from {2} {3} ", textName, valueName, tableName, (whereSql.Length > 0 ? " where " + whereSql : string.Empty));

                cbl.DataTextField = textName;
                cbl.DataValueField = valueName;
                cbl.DataSource = DbHelperSQL.Query(sql);
                cbl.DataBind();
            }

            /// <summary>
            /// 绑定枚举类型到复选框 //Bind(newstype, typeof (EnumClass .NewsType));
            /// </summary>
            /// <param name="cbl"> 复选框</param>
            /// <param name="enumType"> 枚举类型</param>
            public static void Bind(FineUI.CheckBoxList cbl, Type enumType)
            {
                foreach (int i in Enum.GetValues(enumType))
                {
                    cbl.Items.Add(new FineUI.CheckItem(Enum.GetName(enumType, i), i.ToString()));
                }
            }

            /// <summary>
            /// 获取选中文本
            /// </summary>
            /// <param name="cbl">复选框</param>
            /// <returns></returns>
            public static string GetTexts(FineUI.CheckBoxList cbl)
            {
                StringBuilder sb = new StringBuilder();
                foreach (FineUI.CheckItem item in cbl.SelectedItemArray)
                {
                    sb.AppendFormat("{0},",item.Text);
                }
                return sb.ToString().TrimEnd(',');
            }
            
            /// <summary>
            /// 获取选中值
            /// </summary>
            /// <param name="cbl">复选框</param>
            /// <returns></returns>
            public static string GetValues(FineUI.CheckBoxList cbl)
            {
                StringBuilder sb = new StringBuilder();
                foreach (string item in cbl.SelectedValueArray)
                {
                    sb.AppendFormat("{0},",item);
                }
                return sb.ToString().TrimEnd(',');
            }
        }

        public class RadioButtonList
        {
            /// <summary>
            /// 绑定单选框列表
            /// </summary>
            /// <param name="rbl">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            public static void Bind(FineUI.RadioButtonList rbl, string tableName, string textName, string valueName)
            {
                Bind(rbl, tableName, textName, valueName, string.Empty);
            }

            /// <summary>
            /// 绑定单选框列表
            /// </summary>
            /// <param name="rbl">控件</param>
            /// <param name="tableName">表名称</param>
            /// <param name="textName">文本字段</param>
            /// <param name="valueName">值字段</param>
            /// <param name="whereSql">sql条件，注意会有注入危险(不用加where)</param>
            public static void Bind(FineUI.RadioButtonList rbl, string tableName, string textName, string valueName, string whereSql)
            {
                string sql = string.Format("select {0},{1} from {2} {3} ", textName, valueName, tableName, (whereSql.Length > 0 ? " where " + whereSql : string.Empty));

                rbl.DataTextField = textName;
                rbl.DataValueField = valueName;
                rbl.DataSource = DbHelperSQL.Query(sql);
                rbl.DataBind();
            }

            /// <summary>
            /// 绑定枚举类型到单选框 //Bind(newstype, typeof (EnumClass .NewsType));
            /// </summary>
            /// <param name="rbl"> 单选框</param>
            /// <param name="enumType"> 枚举类型</param>
            public static void Bind(FineUI.RadioButtonList rbl, Type enumType)
            {
                foreach (int i in Enum.GetValues(enumType))
                {
                    rbl.Items.Add(new FineUI.RadioItem(Enum.GetName(enumType, i), i.ToString()));
                }
            }
        }
    }
}